/**
 *  *2010-6-25 下午03:22:06  add 
 */
package com.base.myproject.client.HR.Salary;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import com.base.myproject.client.HR.bcode.BcodeSelectDialog;
import com.base.myproject.client.busi.BaseStore;
import com.base.myproject.client.busi.BO.BusiObject;
import com.base.myproject.client.busi.BO.TreeNodeModelData;
import com.base.myproject.client.jdbc.StoreInfo;
import com.base.myproject.client.system.BaseResource;
import com.base.myproject.client.system.Env;
import com.base.myproject.client.ui.BaseGrid;
import com.base.myproject.client.ui.BaseGridPanel;
import com.base.myproject.client.ui.BaseJDBCPanel;
import com.base.myproject.client.ui.celleditor.BaseComboBoxForm;
import com.extjs.gxt.ui.client.Style.SelectionMode;
import com.extjs.gxt.ui.client.data.BaseModelData;
import com.extjs.gxt.ui.client.data.ModelData;
import com.extjs.gxt.ui.client.data.ModelType;
import com.extjs.gxt.ui.client.event.BaseEvent;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.event.MenuEvent;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.extjs.gxt.ui.client.widget.VerticalPanel;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.form.DateField;
import com.extjs.gxt.ui.client.widget.form.FieldSet;
import com.extjs.gxt.ui.client.widget.form.LabelField;
import com.extjs.gxt.ui.client.widget.form.NumberField;
import com.extjs.gxt.ui.client.widget.grid.CellEditor;
import com.extjs.gxt.ui.client.widget.grid.CheckBoxSelectionModel;
import com.extjs.gxt.ui.client.widget.grid.ColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.ColumnModel;
import com.extjs.gxt.ui.client.widget.layout.ColumnData;
import com.extjs.gxt.ui.client.widget.layout.ColumnLayout;
import com.extjs.gxt.ui.client.widget.menu.MenuItem;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.i18n.client.NumberFormat;
import com.google.gwt.user.client.ui.AbstractImagePrototype;

/**
 * 工资的津贴项目 IBadminhd
 * 
 * @author Administrator 2010-6-25 javazgw@gmail.com
 */
public class AddExtSalary extends BaseJDBCPanel {
	public AddExtSalary() {
		init();
	}

	public void init() {
		initWidgetX();
		addbutton.addListener(Events.Select, getListener());
		query.addListener(Events.Select, getListener());
		
		this.complete();
		registerMainStore(store);
	}

	private void initWidgetX() {
		VerticalPanel vpanel = new VerticalPanel();
		vpanel.setSpacing(2);
		vpanel.add(initInnerToolBar());
		vpanel.add(createGrid());
		add(vpanel);
	}

	BcodeSelectDialog<TreeNodeModelData> bsd_add;
	// 金额
	NumberField amount_set = new NumberField();
	// 乘数
	NumberField multiple_set = new NumberField();
	Button addbutton = new Button("添加");
	// 薪金类别
	BaseComboBoxForm<BaseModelData> hr_Salary_Item_editor = new BaseComboBoxForm<BaseModelData>(
			"code", "desc_cn", "hr_Salary_Item", " where salarytype = '2' and code!='A20'",
			false);
	BaseComboBoxForm<BaseModelData> salaryItem = new BaseComboBoxForm<BaseModelData>(
			"code", "desc_cn", "hr_Salary_Item", " where salarytype = '2' and code!='A20'",
			false);
	Button query = new Button("查询");
	DateField datef = new DateField();
	private List<String> bcodeList;  //用于保存Dialog选中的所有员工的bcode，用于添加新的津贴

	private VerticalPanel initInnerToolBar() {
		FieldSet fs = new FieldSet();
		fs.setLayout(new ColumnLayout());
		fs.setHeading("查询操作");
		fs.add(new LabelField("查询月份："), new ColumnData(65));

		datef.getPropertyEditor()
				.setFormat(DateTimeFormat.getFormat("yyyy-MM"));

		fs.add(datef, new ColumnData(100));
		fs.add(new LabelField("查询薪金项目："), new ColumnData(85));
		fs.add(salaryItem, new ColumnData(100));
		fs.add(query, new ColumnData(60));

		fs.setWidth(990);
		fs.setHeight(60);
		fs.setBorders(true);

		FieldSet fs2 = new FieldSet();
		fs2.setHeading("添加操作");
		fs2.setLayout(new ColumnLayout());
		fs2.setWidth(990);
		fs2.setHeight(60);
		bsd_add = new BcodeSelectDialog<TreeNodeModelData>() {
			public void doposted(List<TreeNodeModelData> modeldatalist) {
				if (modeldatalist.size() > 0) {
					String bcode_str = "";
					bcodeList = new ArrayList<String>();
					for (int i = 0; i < modeldatalist.size(); i++) {
						bcode_str = bcode_str + ";"
								+ modeldatalist.get(i).get("bname");
						bcodeList.addAll(getAllBcodelist(modeldatalist.get(i)));
					}
					bcode_str = bcode_str.substring(1, bcode_str.length());
					this.setEmptyText(bcode_str);
				}
			}
		};
		bsd_add.setNeesreselect(false);
		bsd_add.setEmptyText("未选择数据");

		amount_set.setPropertyEditorType(Double.class);

		multiple_set.setPropertyEditorType(Double.class);

		fs2.add(new LabelField("选择人员："), new ColumnData(65));
		bsd_add.setWidth(466);
		fs2.add(bsd_add, new ColumnData(100));

		fs2.add(new LabelField("薪金项目："), new ColumnData(65));
		hr_Salary_Item_editor.setWidth(112);
		fs2.add(hr_Salary_Item_editor, new ColumnData(100));

		fs2.add(new LabelField("金额："), new ColumnData(50));
		amount_set.setWidth(70);
		fs2.add(amount_set, new ColumnData(100));
		fs2.add(new LabelField("倍数："), new ColumnData(50));
		multiple_set.setWidth(70);
		fs2.add(multiple_set, new ColumnData(100));
		fs2.add(addbutton, new ColumnData(100));

		VerticalPanel vpanel = new VerticalPanel();
		vpanel.add(fs);
		vpanel.add(fs2);

		return vpanel;
	}
	
	private List<String> getAllBcodelist(TreeNodeModelData data) {
		List<String> bcodeList = new ArrayList<String>();
		if (data.getChildCount() != 0) {
			for (ModelData node : data.getChildren()) {
				bcodeList.addAll(getAllBcodelist((TreeNodeModelData)node));
			}
		} else {
			if (data.get("bcode") != null) {
				bcodeList.add(data.get("bcode").toString());
			}
		}
		return bcodeList;
	}

	BaseStore<BusiObject> store = null;

	BaseStore<BusiObject> getStore() {
		if (store == null) {
			createStore();
		}
		return store;
	}

	BaseStore<BusiObject> createStore() {
		ModelType type = new ModelType();
		type.setRoot("records");
		type.setRecordName("record");
		type.setTotalName("totle");
		type.addField("icode");
		type.getField("icode").setType(Long.class);
		type.addField("code");
		type.getField("code").setType(String.class);
		type.addField("amount");
		type.getField("amount").setType(Double.class);
		type.addField("multiple");
		type.getField("multiple").setType(Double.class);
		type.addField("status");
		type.getField("status").setType(String.class);
		type.addField("adddate");
		type.getField("adddate").setType(Date.class);
		type.addField("bcode");
		type.getField("bcode").setType(String.class);
		type.addField("createdate");
		type.getField("createdate").setType(Date.class);
		type.addField("createbcode");
		type.getField("createbcode").setType(String.class);
		StoreInfo info = new StoreInfo();
		info.setTablename("hr_salary_ext");
		info.setKeyname(new String[] { "icode" });
		info.setForcenolimit("true");
		info.setSql("select * from hr_salary_ext where 1=2");
		// 关联主表字段
		store = new BaseStore<BusiObject>(type, info);
		return store;
	}

	BaseGrid<BusiObject> grid = null;

	BaseGrid<BusiObject> createGrid() {
		CheckBoxSelectionModel<BusiObject> cbs = new CheckBoxSelectionModel<BusiObject>();
		List<ColumnConfig> columns = new ArrayList<ColumnConfig>();
		columns.add(cbs.getColumn());

		ColumnConfig C2 = new ColumnConfig("code", "薪金项目", 80);
		BaseComboBoxForm<BaseModelData> bsb2 = new BaseComboBoxForm<BaseModelData>(
				"code", "desc_cn", "hr_Salary_Item",
				" where salarytype = '2' and code!='A20'", false);
		C2.setEditor(bsb2.getCelEditor());
		C2.setRenderer(bsb2);
		columns.add(C2);
		ColumnConfig C3 = new ColumnConfig("amount", "金额", 80);
		C3.setNumberFormat(NumberFormat.getFormat("0.00"));
		NumberField C_num3 = new NumberField();
		C_num3.setPropertyEditorType(Double.class);
		C3.setEditor(new CellEditor(C_num3));

		columns.add(C3);
		ColumnConfig C4 = new ColumnConfig("multiple", "倍数", 80);
		NumberField C_num4 = new NumberField();
		C_num4.setPropertyEditorType(Long.class);
		C4.setEditor(new CellEditor(C_num4));
		columns.add(C4);
		ColumnConfig C5 = new ColumnConfig("status", "状态", 80);
		C5.setHidden(true);
		columns.add(C5);
		ColumnConfig C6 = new ColumnConfig("adddate", "发生日期", 80);
		DateField C_data6 = new DateField();
		C_data6.getPropertyEditor().setFormat(
				DateTimeFormat.getFormat("yyyy-MM-dd"));
		C6.setDateTimeFormat(DateTimeFormat.getFormat("yyyy-MM-dd"));
		C6.setEditor(new CellEditor(C_data6));

		columns.add(C6);
		ColumnConfig C7 = new ColumnConfig("bcode", "人员", 80);
		BaseComboBoxForm<BaseModelData> bsb = new BaseComboBoxForm<BaseModelData>(
				"a.bcode", "a.bname", "bcode a, bcode_job b", " where a.bcode = b.bcode and b.employstatus = '在职'", true);
		C7.setRenderer(bsb);
		C7.setEditor(bsb.getCelEditor());
		columns.add(C7);

		ColumnConfig C8 = new ColumnConfig("createdate", "创建日期", 80);

		C8.setDateTimeFormat(DateTimeFormat.getFormat("yyyy-MM-dd"));
		columns.add(C8);
		ColumnConfig C9 = new ColumnConfig("createbcode", "创建人员", 80);
		columns.add(C9);

		ColumnModel cm = new ColumnModel(columns);
		grid = new BaseGrid<BusiObject>(getStore(), cm, true, true) {
			@SuppressWarnings("unchecked")
			public void addnewrecord() {
				HashMap hp = new HashMap();

				hp.put("createdate", new Date());
				hp.put("createbcode", Env.getEnvbcode());
				grid.getStore().add(hp);
			}
		};
		
		MenuItem delete = new MenuItem();
		delete.setText("批量删除津贴");
		delete.setIcon(AbstractImagePrototype.create(BaseResource.INSTANCE.deleterecord()));
		delete.addSelectionListener(new SelectionListener<MenuEvent>() {
			public void componentSelected(MenuEvent ce) {
				int idx = 0;
				for (BusiObject model : grid.getSelectionModel().getSelectedItems()) {
					idx = grid.getStore().indexOf(
							model);
					grid.getStore().remove(grid.getStore().getAt(idx));
				}
				save();
				grid.getStore().reload();
			}
		});
		
		grid.getMenu().add(delete);
		cbs.setSelectionMode(SelectionMode.MULTI);
		grid.setSelectionModel(cbs);
		grid.addPlugin(cbs);
		grid.setLoadMask(true);
		grid.setHeight(320);
		grid.setWidth(990);
		grid.setTrackMouseOver(true);
		
		return grid;
	}

	int sync = 0;
	Listener<BaseEvent> defaultlistener;

	Listener<BaseEvent> getListener() {
		if (defaultlistener != null) {
			return defaultlistener;
		}

		defaultlistener = new Listener<BaseEvent>() {
			public void handleEvent(BaseEvent be) {
				sync++;
				try {
					if (sync == 1) {
						if (be.getType() == Events.Select) {
							if (be.getSource().equals(query)) {
								String sql = "";
								String date = null;
								if (datef.getValue() == null
										&& salaryItem.getValueCode() == null) {
									MessageBox.alert("提示", "必须输入查询条件！", null);
								}

								if (datef.getValue() != null
										&& salaryItem.getValueCode() == null) {
									DateTimeFormat dtf = DateTimeFormat
											.getFormat("yyyy-MM-dd");
									date = dtf.format(datef.getValue());
									sql = " select * from hr_salary_ext  where datediff(month,'"
											+ date
											+ "',adddate )=0 order  by adddate desc";
									store.getStoreinfo().setSql(sql);
									store.reload();
								} else if (datef.getValue() == null
										&& salaryItem.getValueCode() != null) {
									sql = " select * from hr_salary_ext  where code='"
											+ salaryItem.getValueCode()
											+ "' order  by adddate desc";
									store.getStoreinfo().setSql(sql);
									store.reload();
								} else if (datef.getValue() != null
										&& salaryItem.getValueCode() != null) {
									DateTimeFormat dtf = DateTimeFormat
											.getFormat("yyyy-MM-dd");
									date = dtf.format(datef.getValue());
									sql = " select * from hr_salary_ext  where datediff(month,'"
											+ date
											+ "',adddate )=0 and code='"
											+ salaryItem.getValueCode()
											+ "' order  by adddate desc";
									store.getStoreinfo().setSql(sql);
									store.reload();
								}
							} else if (be.getSource().equals(addbutton)) {
								List<TreeNodeModelData> selectchecklist = bsd_add
										.getTree().getCheckedSelection();
								for (String bcode : bcodeList) {
									BusiObject bo = new BusiObject();
									bo.set("code", hr_Salary_Item_editor
											.getValueCode());
									bo.set("amount", amount_set.getValue());
									bo.set("multiple", multiple_set.getValue());
									bo.set("bcode", bcode);
									bo.set("adddate", new Date());
									bo.set("createdate", new Date());
									bo.set("createbcode", Env.getEnvbcode());
									getStore().add(bo);
								}

								bsd_add.deselectall();
								bsd_add.setEmptyText("未选择数据");
							}
						}
					}
				} finally {
					sync--;
				}
			}

		};
		return defaultlistener;
	}

	/**
	 * 将数据导出到excel
	 *//*
	public void Export_excel() {
		ExcelObject eo = Grid2ExcelBO.getInstance().getEO(grid.getBg());
		DownExcelDialog.getInstance().javascript(eo);

	}*/

}
